package main

import (
	"encoding/json"
	"fmt"
	"mcp-clarification-service/internal/config"
	"mcp-clarification-service/internal/tools"
	"mcp-clarification-service/pkg/logger"
	"net/http"
	"os"
)

func main() {
	cfg := config.DefaultConfig()
	log := logger.New("info")

	log.Info("Starting mock GUI server on port %d", cfg.GUI.Port)

	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
	})

	http.HandleFunc("/ask", func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Questions []tools.Question `json:"questions"`
			Timeout   int              `json:"timeout"`
		}
		json.NewDecoder(r.Body).Decode(&req)

		log.Info("Received %d questions", len(req.Questions))

		// 模拟响应
		answers := make([]tools.Answer, len(req.Questions))
		for i, q := range req.Questions {
			log.Info("Question %d: %s (type: %s)", i+1, q.Question, q.Type)
			answers[i] = tools.Answer{
				ID:   q.ID,
				Type: q.Type,
			}
			if q.Type == "single" {
				idx := 0
				answers[i].SelectedIndex = &idx
				log.Info("  -> Mock answer: selected index 0")
			} else if q.Type == "multiple" {
				answers[i].SelectedIndices = []int{0}
				log.Info("  -> Mock answer: selected indices [0]")
			} else {
				answers[i].Text = "Mock answer for free text question"
				log.Info("  -> Mock answer: %s", answers[i].Text)
			}
		}

		resp := map[string]interface{}{
			"answers":   answers,
			"cancelled": false,
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(resp)
	})

	addr := fmt.Sprintf(":%d", cfg.GUI.Port)
	log.Info("Mock GUI server ready at http://localhost%s", addr)
	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Error("Server error: %v", err)
		os.Exit(1)
	}
}
